﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using umbraco;
using umbraco.cms.businesslogic.media;
using umbraco.cms.businesslogic;
using System.Net;

namespace Decode.Umb
{
	public partial class Save : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			// if the user exited the editor close the window
			if (Request.QueryString["close"] == "1")
			{
				CloseWindow();
				return;
			}

			// get media id and media key
			if (Request.QueryString["id"] == null)
				return;
			string[] qry = Request.QueryString["id"].Split('|');

			int mediaId;
			if (!int.TryParse(qry[0], out mediaId))
				return;
			string mediaKey = qry[1];

			bool saveAsNew = qry[2] == "1";
			string saveAsName = string.Empty;
			if (saveAsNew)
				saveAsName = qry[3];

			// get media
			Media m = new Media(mediaId);
			if (m == null)
				return;

			// verify our hashed key matches the media's
			if (Decode.Umb.Hash.GetMediaMd5Sum(m) != mediaKey)
			{
				HandleError();
				return;
            }

            //if (Request.Files.Count > 0)
            if(!String.IsNullOrEmpty(Request.QueryString["image"]))
			{
				//if (Request.Files["image"].ContentLength > 0)
				//{
					// settings
					//HttpPostedFile file = Request.Files["image"];
					//string imageType = Request.Form["type"];                    
	                string urlImage = Request.QueryString["image"];
                    string imageType = Path.GetExtension(urlImage).Remove(0,1);

					// verify the returned file is an image file
					if (imageType != "jpg" && imageType != "png" && imageType != "gif" && imageType != "bmp")
					{
						HandleError("The selected image type can not be saved.");
						return;
					}

					// get the saved image for thumbnail use
                    WebClient webClient = new WebClient();
					//Image image = Image.FromStream(file.InputStream);
                    Image image = null;
					string mediaName = string.Empty, savePath = string.Empty, thumbnailPath = string.Empty, mediaPath = string.Empty;
					if (!saveAsNew)
					{
						mediaName = Path.GetFileNameWithoutExtension(m.getProperty("umbracoFile").Value.ToString()) + "." + imageType;
						mediaPath = Path.GetDirectoryName(m.getProperty("umbracoFile").Value.ToString().Replace("/", "\\")) + "\\";
						savePath = Server.MapPath(string.Concat(mediaPath, mediaName));
						thumbnailPath = string.Concat(mediaPath, mediaName.Replace("." + imageType, "_thumb.jpg"));

                        //file.SaveAs(savePath);
                        webClient.DownloadFile(urlImage, savePath);
                        image = Image.FromFile(savePath);
						GenerateThumbnail(ref image, 100, image.Width, image.Height, thumbnailPath);
					}
					else
					{
						mediaName = string.Concat(saveAsName, ".", imageType);
						int parentId;
						try
						{
							parentId = m.Parent.Id;
						}
						catch
						{
							parentId = -1;
						}
						m = Media.MakeNew(saveAsName, MediaType.GetByAlias(m.ContentType.Alias), m.User, parentId);
						mediaPath = string.Concat("\\media\\", m.getProperty("umbracoFile").Id, "\\");
						savePath = mediaPath;
						thumbnailPath = string.Concat(savePath, mediaName.Replace("." + imageType, "_thumb.jpg"));
						Directory.CreateDirectory(Server.MapPath(savePath));
						string filePath = string.Concat(Server.MapPath(savePath), mediaName);

                        //file.SaveAs(filePath);
                        webClient.DownloadFile(urlImage, savePath);
                        image = Image.FromFile(savePath);
						GenerateThumbnail(ref image, 100, image.Width, image.Height, thumbnailPath);
					}

					// update media data
                    FileInfo fileInfo = new FileInfo(savePath);
					if (m.getProperty("umbracoFile") != null)
						m.getProperty("umbracoFile").Value = mediaPath.Replace("\\", "/") + mediaName;
					if (m.getProperty("umbracoHeight") != null)
						m.getProperty("umbracoHeight").Value = image.Height.ToString();
					if (m.getProperty("umbracoWidth") != null)
						m.getProperty("umbracoWidth").Value = image.Width.ToString();
					if (m.getProperty("umbracoBytes") != null)
						m.getProperty("umbracoBytes").Value = fileInfo.Length.ToString();
					if (m.getProperty("umbracoExtension") != null)
						m.getProperty("umbracoExtension").Value = imageType;

					m.Save();
					m.XmlGenerate(new System.Xml.XmlDocument());

					//Fill the cache again.
					library.GetMedia(m.Id, false);

					image.Dispose();
				//}
			}

			CloseWindow(saveAsNew, m);
		}

		void HandleError()
		{
			HandleError("Ups... An unknown error occurred. The image could not be saved.");
		}

		void HandleError(string text)
		{
			string jscript = String.Format("opener.location.reload();alert('{0}');window.close();", text);
			ClientScript.RegisterStartupScript(this.GetType(), "error", jscript, true);
		}

		void CloseWindow(bool saveAsNew = false, Media m = null)
		{
			string syncTree = "opener.location.reload();";
			if (m != null && saveAsNew)
				syncTree = string.Concat("opener.location = '/umbraco/editMedia.aspx?id=", m.Id, "'; opener.UmbClientMgr.mainTree().syncTree('", m.Path, "', true);");
			ClientScript.RegisterStartupScript(this.GetType(), "close", string.Concat(syncTree, " window.close();"), true);
		}

		void GenerateThumbnail(ref Image image, int maxWidthHeight, int fileWidth, int fileHeight, string thumbnailFileName)
		{
			// Generate thumbnail
			float fx = (float)fileWidth / (float)maxWidthHeight;
			float fy = (float)fileHeight / (float)maxWidthHeight;
			// must fit in thumbnail size
			float f = Math.Max(fx, fy); //if (f < 1) f = 1;
			int widthTh = (int)Math.Round((float)fileWidth / f); int heightTh = (int)Math.Round((float)fileHeight / f);

			// fixes for empty width or height
			if (widthTh == 0)
				widthTh = 1;
			if (heightTh == 0)
				heightTh = 1;

			// Create new image with best quality settings
			using (Bitmap bp = new Bitmap(widthTh, heightTh))
			{
				using (Graphics g = Graphics.FromImage(bp))
				{
					g.SmoothingMode = SmoothingMode.HighQuality;
					g.InterpolationMode = InterpolationMode.HighQualityBicubic;
					g.PixelOffsetMode = PixelOffsetMode.HighQuality;

					// Copy the old image to the new and resized
					Rectangle rect = new Rectangle(0, 0, widthTh, heightTh);
					g.DrawImage(image, rect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);

					// Copy metadata
					ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
					ImageCodecInfo codec = null;
					for (int i = 0; i < codecs.Length; i++)
					{
						if (codecs[i].MimeType.Equals("image/jpeg"))
							codec = codecs[i];
					}

					// Set compresion ratio to 90%
					EncoderParameters ep = new EncoderParameters();
					ep.Param[0] = new EncoderParameter(Encoder.Quality, 90L);

					// Save the new image
					bp.Save(Server.MapPath(thumbnailFileName), codec, ep);
				}
			}
		}
	}
}